package com.ryf.maven.dao;

import com.ryf.maven.entity.Admin;
import com.ryf.maven.entity.Student;
import com.ryf.maven.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @ClassName AdminDao
 * @Author L-Cohen
 * @date 2020.12.03 18:54
 */
public class AdminDao {

    public static Admin getAdmin(ResultSet resultSet) throws SQLException {
        String id = resultSet.getString("id");
        String password = resultSet.getString("password");

        Admin admin = new Admin();
        admin.setId(id);
        admin.setPassword(password);

        return admin;
    }

    public static List<Admin> getAdmin(){
        List<Admin> admins = new ArrayList<Admin>();
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareCall("select * from admin");
            resultSet = statement.executeQuery();
            while (resultSet.next())
            {
                Admin admin = getAdmin(resultSet);
                admins.add(admin);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        DBUtil.close(resultSet, statement, connection);
        return admins;
    }

    public static Admin getAdminPassword(String id){
        Connection connection = DBUtil.getConnection();
        String sql = "select * from admin where id = ?";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Admin admin = null;
        try {
            statement = connection.prepareCall(sql);

            statement.setString(1, id);
            resultSet = statement.executeQuery();
            if (resultSet != null && resultSet.next())
            {
                admin = getAdmin(resultSet);
            }
            DBUtil.close(resultSet, statement, connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admin;
    }

    public static void main(String[] args) {
        Admin admin = getAdminPassword("20066");
        System.out.println(admin.getPassword());
    }

}
